package com.sw.bbs.common.advice;

import com.sw.bbs.common.util.JacksonUtil;
import com.sw.bbs.common.vo.RestResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * RestResponseWapper
 *
 * @author Johnathan
 */
@ControllerAdvice("com.sw.bbs")
public class RestResponseWapper implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Nullable
    @Override
    public Object beforeBodyWrite(@Nullable Object objectResponseEntity, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        Object restResponse = objectResponseEntity;

        if (methodParameter.getMethod().getName().equals("uploadEditor")){
            return restResponse;
        }

        if (!(objectResponseEntity instanceof RestResponse)) {
            restResponse = new RestResponse<>(objectResponseEntity);
        }

        if (mediaType.includes(MediaType.TEXT_PLAIN) || mediaType.includes(MediaType.APPLICATION_JSON_UTF8) || mediaType.includes(MediaType.APPLICATION_JSON)) {
            if (objectResponseEntity instanceof String) {
                restResponse = JacksonUtil.writeObjectToJSON(restResponse);
            }
        }

        return restResponse;
    }
}
